#!/usr/bin/env bash
# ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ----
# Function :CentOS7.X NFS安装脚本
# Platform :RedHatEL7.x Based Platform
# Version  :1.0
# Date     :2020-08-28
# Author   :mugoLH
# Contact  :houxiaoshuai@baidu.com & hxsaj@126.com
# Company  :
# depend on:
# ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ----
set -e
#  变量列表 List of common variables
# ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ----
HOST_LIST=./hostname.list

#  函数列表 Function list
########## ########## ########## ########## ########## ########## #
#  提示的色彩    echo -e "\033[38;46m 色彩测试-提示 \033[0m"
function show_notice() {
    echo -e "\033[34;46m $@ \033[0m" >&1
}
#  警告的色彩    echo -e "\033[35;46m 色彩测试-警告 \033[0m"
function show_warning() {
    echo -e "\033[35;46m $@ \033[0m" >&2
}
#  报错的色彩   echo -e "\033[1;31;46m 色彩测试-错误 \033[0m"
function show_error() {
    echo -e "\033[1;31;46m $@ \033[0m" >&2

}

# 免密
function ssh_key_copy(){
	#  静默生成密钥对
	if [ ! -f ~/.ssh/id_rsa ];then
		ssh-keygen -f ~/.ssh/id_rsa -t rsa -N '' >/dev/null 2>&1
	fi
	#  不验证主机写入known_hosts 文件，避开DNS解析
	sed -i '/StrictHostKeyChecking/s/^#//; /StrictHostKeyChecking/s/ask/no/' /etc/ssh/ssh_config
	sed -i "/#UseDNS/ s/^#//; /UseDNS/ s/yes/no/" /etc/ssh/sshd_config

	#  分发密钥对
	cat ${1} | grep -v ^# | while read host ip pwd; do
		#  免密到目标服务器
		sshpass -p ${pwd} ssh-copy-id -f ${ip} >/dev/null 2>&1 && show_notice "[ SUCCEE ] 本机免密到：${ip}  successful !"
		#  设置主机名
		ssh -nq ${ip} "hostnamectl set-hostname ${host}" && show_notice "[ SUCCEE ] 主机名设置：${ip}  ${host} successful !"
		#  配置ssh文件分发
		scp -rpq /etc/ssh/ssh_config ${ip}:/etc/ssh/ssh_config
		scp -rpq /etc/ssh/sshd_config ${ip}:/etc/ssh/sshd_config
		ssh -nq ${ip} "systemctl restart sshd"

		#  host文件修改
		echo ${ip} ${host} >> /etc/hosts
	done
	#  分发host文件到目标服务器
	cat ${1} | grep -v ^# | while read host ip pwd; do
		scp -rpq /etc/hosts ${ip}:/etc/  && show_notice "[ SUCCEE ] 主机hosts文件分发到：${ip} successful !"
		#  分发密钥对到目标服务器
		#scp -rpq ~/.ssh/id_rsa* ${ip}:~/.ssh/ && show_notice " 密钥对分发到：${ip} successful !"
		scp -rpq ~/.ssh ${ip}:~/ && show_notice "[ SUCCEE ] 密钥对分发到：${ip} successful !"
	done
}
ssh_key_copy ${HOST_LIST}